from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules import db
from comment.modules.Letter import Letter_Detail, Letter
from comment.modules.user import User
from comment.utils.decorators import login_required
from financial.resources.letter.serializer import LetterPaginateSerializer


class Letter_Res(Resource):
    """
    发送消息的资源类
    """

    # 使用了登录拦截器
    method_decorators = [login_required]

    def post(self):
        """
        发送消息
        :return:
        """
        rp = RequestParser()
        rp.add_argument('title', required=True)
        rp.add_argument('group')
        rp.add_argument('rec_id')
        rp.add_argument('content', required=True)

        args = rp.parse_args()
        title = args.get('title')
        group = args.get('group')
        rec_id = args.get('rec_id')
        content = args.get('content')

        # 发送消息的用户id
        uid = g.user_id
        user = User.query.filter(User.id == uid).first()

        # 第一种，群发消息，group是有三个值，2表示全体用户，0表示普通用户，1表示管理用户
        if group == '0' or group == '1':
            rec_list = User.query.filter(User.role == int(group)).all()

        if group == '2':
            rec_list = User.query.all()

        # 第二种，单个用户发送消息
        if rec_id:
            rec_user = User.query.filter(User.id == rec_id).first()
            if rec_user:
                rec_list = [rec_user]

        new_letter_detail = Letter_Detail(title=title, detail=content)
        db.session.add(new_letter_detail)
        db.session.flush()

        for rec_user in rec_list:
            # 给每个用户都发送消息
            letter = Letter(sendID=user.username, recID=rec_user.id, detail_id=new_letter_detail.id, state=0)
            db.session.add(letter)

        db.session.commit()
        return {'msg': 'ok'}

    def get(self):
        """
        当前用户收到的消息列表(分页)
        :return:
        """

        uid = g.user_id  # 当前登录的用户ID
        user = User.query.filter(User.id == uid).first()
        rp = RequestParser()
        rp.add_argument('curPage', required=True)  # 访问的页号
        rp.add_argument('perPage', required=True)  # 每页显示数据的条数
        args = rp.parse_args()
        curPage = int(args.get('curPage'))
        perPage = int(args.get('perPage'))

        # letter_list：是Pagination类型。包含分页的数据，同时在items属性中包含消息列表数据
        letter_list = Letter.query.filter(Letter.recID == uid).paginate(curPage, perPage, error_out=False)
        dict_data = LetterPaginateSerializer(letter_list).to_dict()
        return {'msg': 'ok', 'data': dict_data}

    def put(self):
        """更新已读状态"""
        rp = RequestParser()
        rp.add_argument('message_id', required=True)
        args = rp.parse_args()
        m_id = args.get('message_id')

        letter = Letter.query.filter(Letter.id == m_id).first()

        if letter:
            letter.state = 1
            db.session.commit()
            return {'msg': 'ok'}

        else:
            return {'message': '此消息不存在', 'code': 20005}

    def delete(self):
        """
        删除消息
        :return:
        """
        rp = RequestParser()
        rp.add_argument('message_id', required=True)
        args = rp.parse_args()
        m_id = args.get('message_id')

        letter = Letter.query.filter(Letter.id == m_id)

        if letter:
            letter.delete()
            db.session.commit()
            return {'msg': 'ok'}

        else:
            return {'message': '此消息不存在', 'code': 20005}
